﻿using IOP.OpenType.Tables;
using IOP.OpenType;
using System;
using System.Buffers;
using System.IO;
using System.Threading.Tasks;

namespace IOP.Codec.OpenType
{
    /// <summary>
    /// 头文件加载器
    /// </summary>
    public class HeadTableLoader
    {
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="entry"></param>
        /// <returns></returns>
        public async Task<HeadTable> Load(FileStream stream, TableEntry entry)
        {
            uint offset = entry.Offset;
            uint length = entry.Length;
            stream.Seek(offset, SeekOrigin.Begin);
            Memory<byte> bytes = new byte[length];
            await stream.ReadAsync(bytes);
            var table = ReadHead(bytes);
            table.Entry = entry;
            return table;
        }

        private HeadTable ReadHead(Memory<byte> data)
        {
            ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>(data);
            SequenceReader<byte> reader = new SequenceReader<byte>(sequence);
            HeadTable headTable = new HeadTable();
            reader.TryReadBigEndian(out short majV);
            reader.TryReadBigEndian(out short minV);
            reader.TryReadBigEndian(out int rVersion);
            reader.TryReadBigEndian(out int cSa);
            reader.TryReadBigEndian(out int mN);
            reader.TryReadBigEndian(out short flags);
            reader.TryReadBigEndian(out short uPE);
            reader.TryReadBigEndian(out long create);
            reader.TryReadBigEndian(out long modified);
            reader.TryReadBigEndian(out short xMin);
            reader.TryReadBigEndian(out short yMin);
            reader.TryReadBigEndian(out short xMax);
            reader.TryReadBigEndian(out short yMax);
            reader.TryReadBigEndian(out short macS);
            reader.TryReadBigEndian(out short lowestR);
            reader.TryReadBigEndian(out short fontDirH);
            reader.TryReadBigEndian(out short indexTo);
            reader.TryReadBigEndian(out short glyphDF);
            headTable.MajorVersion = (ushort)majV;
            headTable.MinorVersion = (ushort)minV;
            headTable.FontRevision = rVersion;
            headTable.CheckSumAdjustment = (uint)cSa;
            headTable.MagicNumber = (uint)mN;
            headTable.Flags = (ushort)flags;
            headTable.UnitsPerEm = (ushort)uPE;
            headTable.Created = create;
            headTable.Modified = modified;
            headTable.XMin = xMin;
            headTable.YMin = yMin;
            headTable.XMax = xMax;
            headTable.YMax = yMax;
            headTable.MacStyle = (ushort)macS;
            headTable.LowestRecPPEM = (ushort)lowestR;
            headTable.FontDirectionHint = fontDirH;
            headTable.IndexToLocFormat = indexTo;
            headTable.GlyphDataFormat = glyphDF;
            return headTable;
        }
    }
}
